package login

import (
	"context"
	"time"

	"server-go/api/reward/internal/svc"
	"server-go/api/reward/internal/types"
	"server-go/api/reward/internal/util"
	"server-go/rpc/reward/types/reward"

	"github.com/zeromicro/go-zero/core/logx"
)

type AccountLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AccountLogic {
	return &AccountLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AccountLogic) Account(req *types.AccountInput) (resp *types.AccountOutput, err error) {
	resp = new(types.AccountOutput)
	// 登录
	res, err := l.svcCtx.RewardRpc.Account(l.ctx, &reward.AccountInput{
		PassWord: req.PassWord,
		UserName: req.UserName,
	})
	if err != nil {
		return resp, err
	}
	if res.Data != "success" {
		resp.Data = res.Data
		return resp, nil
	}
	// 生成jwt token
	now := time.Now().Unix()
	token, err := util.GetJwtToken(l.svcCtx.Config.Auth.AccessSecret, res.BaseUserInfo.UserName, 2, now, l.svcCtx.Config.Auth.AccessExpire)
	if err != nil {
		return resp, err
	}
	resp.Data = res.Data
	resp.BaseUserInfo = &types.Account{
		NickName:  res.BaseUserInfo.NickName,
		Email:     res.BaseUserInfo.Email,
		Gender:    res.BaseUserInfo.Gender,
		UserIntro: res.BaseUserInfo.UserIntro,
		UserName:  res.BaseUserInfo.UserName,
		Money:     res.BaseUserInfo.Money,
		Token:     token,
	}
	return resp, nil
}
